package com.stb.llh.controller;

import com.stb.llh.entity.CY;
import com.stb.llh.entity.Emotion;
import com.stb.llh.entity.PreLife;
import com.stb.llh.entity.User;
import com.stb.llh.service.EmotionService;
import com.stb.llh.service.LifeService;
import com.stb.llh.service.UserService;
import com.stb.llh.util.NotFound;
import com.stb.llh.util.ResJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author Lee
 * @Date 2021/11/3
 * @Description
 */

@Controller
@RequestMapping("/user")
public class UserController {

//    缓存
    private volatile ConcurrentHashMap<String ,List<CY>> curl = new ConcurrentHashMap<>();

    public List<CY> getCurl(String key){
        System.out.println("存储：");
        for (String s : curl.keySet()) {
            System.out.println("*******"+s);

        }
        if(curl.contains(key)){
            System.out.println("走捷径咯*****************");
            return curl.get(key);
        }
       return null;
    }

    public void setCurl(String key,List<CY> cys){

        curl.put(key,cys);

    }

    @Autowired
    private UserService userService;

    @Autowired
    private EmotionService emotionService;


    @Autowired
    private LifeService lifeService;


    @GetMapping("/emotion")
    public String emotion(HttpServletRequest req){
        System.out.println("emotion");
        List<Emotion> emotions = emotionService.getEmotions();
//        System.out.println(emotions);

        req.setAttribute("emos",emotions);



        return "user/ai/qin";
    }

    @PostMapping("/emotionRes")
    @ResponseBody
    public String emotionRes(HttpServletRequest req, HttpServletResponse res,String username, String comments) throws UnsupportedEncodingException {
        System.out.println(username);
        System.out.println(comments);

        if("".equalsIgnoreCase(comments)){
            ResJson.getError("吐槽失败");
        }



        res.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        String url = "http://localhost:5000/emotion?con="+comments;
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        String body = responseEntity.getBody();
        String b[] = body.split(" ");
        body =  b[0];
        System.out.println(body);


        double d = Double.parseDouble(body);
        boolean flag = emotionService.insertEmotion(username, comments, d);

        if(!flag){
            ResJson.getError("吐槽失败");
        }


        return ResJson.getSuccess("吐槽成功");
    }



    @GetMapping("/live")
    public String live(){
        return "user/ai/live";
    }



    @PostMapping("/liveRes")
    @ResponseBody
    public String liveRes(HttpServletRequest req, String username,String date, String hour,String sex) throws ParseException {
        System.out.println(date);
        System.out.println(hour);
        System.out.println(sex);

        if("".equalsIgnoreCase(date) || "".equalsIgnoreCase(hour)){
            return ResJson.getError("投放失败");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date time = sdf.parse(date);
        Calendar c = Calendar.getInstance();
        c.setTime(time);

        System.out.println(c.get(Calendar.YEAR));
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int h = Integer.parseInt(hour.split(":")[0]);

        int r;
        if("男".equalsIgnoreCase(sex)){
            r = 2;
        }
        else{
            r = 1;
        }





        System.out.println(year + " "+ month + " " +day + " "+ h );

        String url = "http://localhost:5000/live?year="+year+"&month="+month+"&day="+day+"&hour="+h+"&sex="+r;
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        String body = responseEntity.getBody();
        System.out.println(body);
//        String b[] = body.split(" ");
//        body =  b[0];
//        System.out.println(body);

        if("".equalsIgnoreCase(body)){
            return ResJson.getError("生成错误！");
        }



        return ResJson.getSuccess(body);
    }


    @GetMapping("/life")
    public String life(){
        return "life/index";
    }

    @PostMapping("/lifeRes")
    @ResponseBody
    public String lifeRes(HttpServletRequest req,int age,double livePercent,String con){
        System.out.println(age);
        System.out.println(con);
        System.out.println(livePercent);

        con = con.replace("<p>","").replace("<p/>","");

        User u = (User)req.getSession().getAttribute("user");
        String username = u.getUsername();
        lifeService.insertLife(new PreLife(username,age,livePercent,con));
        return ResJson.getSuccess("ok");
    }


    @GetMapping("/video")
    public String video(){
        return "user/ai/video";
    }

    @PostMapping("/videoRes")
    @ResponseBody
    public String videoRes(HttpServletRequest req, String cy){

        System.out.println(cy);
        List<CY> cyList = getCurl(cy);
        if(cyList!=null){

            return  ResJson.getSuccess(cyList);
        }

        String url = "http://localhost:5000/ciyu?kws="+cy;
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        String body = responseEntity.getBody();

        if("error".equalsIgnoreCase(body)){
            return ResJson.getError("error");
        }

//        System.out.println(body);
        body = body.replace("[","").replace("(","");
        String[] split = body.split("\\),");
        List<CY> res = new ArrayList<>();
        for (String s : split) {
            String[] split1 = s.replace(")]","").split(",");
            res.add(new CY(split1[0],split1[1],Double.parseDouble(split1[2])));
        }

        res.sort((o1,o2)->Double.compare(o2.getRate(), o1.getRate()));
//        System.out.println(res);
        req.setAttribute("cy",res);

        setCurl(cy,res);




//        String b[] = body.split(" ");
//        body =  b[0];
//        System.out.println(body);

        if("".equalsIgnoreCase(body)){
            return ResJson.getError("生成错误！");
        }



        return ResJson.getSuccess(res);


    }


}
